<template>
    <div>
        <el-card>
            <template #header>
                <div>
                    <el-form :model="formData" ref="form" label-width="100px" :inline="false">
                        <el-row :gutter="20">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="计划名称" prop="planName">
                                    <el-input v-model="formData.planName" style="width: 350px;"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="计划类型" prop="planType">
                                    <el-radio-group v-model="formData.planType">
                                        <el-radio v-for="item in getPlanType" :key="item.value" :label="item.label"
                                            :value="item.value"></el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" :offset="0">
                                <el-form-item v-if="formData.planType === 1" label="选择订单" prop="salesOrderId">
                                    <el-input style="width: 300px; margin-right: 10px;" v-model="formData.salesOrderId"
                                        placeholder="请选择订单" disabled></el-input>
                                    <el-button type="primary" @click="showOrderDialog">选择订单</el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="开始时间" prop="startDate">
                                    <el-date-picker type="datetime" placeholder="选择日期" v-model="formData.startDate"
                                        style="width: 350px;" value-format="YYYY-MM-DD 0HH:mm:ss" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" :offset="0">
                                <el-form-item label="结束时间" prop="endDate">
                                    <el-date-picker type="datetime" placeholder="选择日期" v-model="formData.endDate"
                                        style="width: 350px;" value-format="YYYY-MM-DD 0HH:mm:ss" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
            </template>

            <!-- 产品列表 -->
            <el-card style="margin-top: 20px;">
                <template #header>
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span>产品列表</span>
                        <div>
                            <el-button type="primary" size="small" @click="showProductDialog"
                                v-if="formData.planType === 2">
                                选择产品
                            </el-button>
                        </div>
                    </div>
                </template>

                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="产品编号">
                            <el-input v-model="products.productId" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="产品名称">
                            <el-input v-model="products.materialName" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="规格型号">
                            <el-input v-model="products.specificationsAndModels" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="单位">
                            <el-input v-model="products.quoteDetailsUnit" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="计划数量">
                            <el-input v-model="products.quoteDetailsNumberOfSales" readonly>
                                <template #default="{ row }">
                                    <el-tag>{{ row.quoteDetailsNumberOfSales }}</el-tag>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="工艺路线">
                            <el-select v-model="products.routingId" style="width: 350px;" placeholder="请选择工艺路线">
                                <el-option v-for="item in options" :key="item.processRouteId"
                                    :label="item.processRouteName" :value="item.processRouteId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-card>

            <el-form-item style="margin-top: 20px;">
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="cancelForm">取消</el-button>
            </el-form-item>
        </el-card>

        <!-- 订单选择弹窗 -->
        <el-dialog v-model="orderDialogVisible" title="选择报价单" width="40%">
            <el-table :data="orderList.records" @row-click="selectOrder" highlight-current-row style="width: 100%">
                <el-table-column prop="quotationId" label="报价单编号" width="120" />
                <el-table-column prop="quotationHeadOfSales" label="负责人" width="120" />
                <el-table-column prop="quotationCustomerResourcesId" label="客户编号" width="120" />
                <el-table-column prop="quotaionShippingTime" label="发货时间" width="120" />
                <el-table-column prop="quotationState" label="状态" width="120" />
            </el-table>



            <!-- 订单产品详情 -->
            <el-card style="margin-top: 20px;">
                <template #header>
                    <div>报价单产品列表</div>
                </template>
                <el-table :data="productData" border>
                    <el-table-column prop="productId" label="产品编号" width="150" />
                    <el-table-column prop="materialName" label="产品名称" width="150" />
                    <el-table-column prop="quoteDetailsUnit" label="单位" width="100" />
                    <el-table-column prop="quoteDetailsNumberOfSales" label="销售数量" width="120" />
                    <el-table-column label="操作" width="120">
                        <!-- 添加变为已添加 -->
                        <template #default="{ row }">
                            <el-button v-if="!row.isAdded" type="success" size="small" @click="addProduct(row)">
                                添加
                            </el-button>
                            <el-button v-else type="info" size="small" disabled>
                                已添加
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>



            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="orderDialogVisible = false">取消</el-button>
                    <el-button type="primary" size="default" @click="addOrder(row)">
                        添加
                    </el-button>
                </span>
            </template>
        </el-dialog>


        <!-- 产品选择弹窗 -->
        <el-dialog v-model="productDialogVisible" title="选择产品" width="80%">
            <div style="margin-bottom: 20px;">
                <el-input v-model="productSearch" placeholder="输入产品编号或名称搜索" style="width: 300px; margin-right: 10px;"
                    clearable @clear="handleProductSearchClear" @keyup.enter="handleProductSearch">
                    <template #append>
                        <el-button icon="search" @click="handleProductSearch" />
                    </template>
                </el-input>
                <el-button type="primary" @click="confirmProductSelection">确认选择</el-button>
            </div>

            <el-table :data="filteredProductList" border style="width: 100%">
                <el-table-column prop="materialId" label="产品编号" width="150" sortable />
                <el-table-column prop="materialName" label="产品名称" width="150" sortable />
                <el-table-column prop="specificationsAndModels" label="规格型号" width="150" />
                <el-table-column prop="unit" label="单位" width="100" />
                <el-table-column prop="safetyStock" label="安全库存" width="120" sortable>
                    <template #default="{ row }">
                        <el-tag :type="row.safetyStock < 100 ? 'danger' : 'success'">
                            {{ row.safetyStock }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="计划数量" width="150">
                    <template #default="{ row }">
                        <el-input-number v-model="row.planQuantity" :min="1" :max="row.safetyStock" size="small" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                        <el-button v-if="!row.isAdded" type="success" size="small" @click="addProducts(row)">
                            添加
                        </el-button>
                        <el-button v-else type="info" size="small" disabled>
                            已添加
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination small layout="prev, pager, next" :total="productLists.length" :page-size="10"
                v-model:current-page="productPage" style="margin-top: 20px;" />
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, defineEmits, computed, onMounted } from 'vue'
import request from '@/api/request'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const props = defineProps(['data'])
const emit = defineEmits(['ref-table'])

// 表单数据保持不变
const formData = ref({})

//订单类型
const getPlanType = [
    { value: 1, label: '订单计划' },
    { value: 2, label: '库存计划' },
]

// 订单相关状态
const orderDialogVisible = ref(false)

const selectedOrder = ref(null)

const orderList = ref({
    current: 1,
    size: 100,
    total: 0,
    records: []
}) // 存储从后端获取的报价单列表

// 打开订单选择弹窗并加载报价单数据
const showOrderDialog = async () => {
    orderDialogVisible.value = true;
    request({
        url: '/quotation/where',
        method: 'get',
        params: {
            current: orderList.value.current,
            size: orderList.value.size,
        }
    }).then(res => {
        orderList.value = res.data
    })
}

const productData = ref([])
// 选择报价单，获取详情及明细
const selectOrder = (row) => {
    selectedOrder.value = row
    //查询产品
    request({
        url: '/quotation',
        method: 'get',
        params: {
            quotationId: row.quotationId
        }
    }).then(res => {
        console.log(res.data.records[0].quoteDetails);
        let productList = res.data.records[0].quoteDetails
        productData.value = [] // 清空之前的数据

        productList.forEach(item => {
            let p = {
                productId: item.quoteDetailsProductsId,
                quoteDetailsUnit: item.quoteDetailsUnit,
                quoteDetailsNumberOfSales: item.quoteDetailsNumberOfSales,
                isAdded: false // 初始化添加状态为false
            }
            console.log(p);
            productData.value.push(p)
        })
        console.log(productData.value)
    })
    request({
        url: "/material/index",
        method: "get",
        params: {
            page: 1,
            size: 10000,
        }
    }).then(res => {
        let materialTableData = res.data.records//物料数据
        console.log(materialTableData);
        productData.value.forEach(item => {
            let material = materialTableData.find(p => p.materialId === item.productId)
            if (material) {
                item.specificationsAndModels = material.specificationsAndModels
                item.materialName = material.materialName
            }
        })
        console.log(productData.value);
    })
    //每次选择报价单，清空产品列表
    productData.value = []
}

let bomList = ref([])

const products = ref({})

//添加产品
const addProduct = (row) => {
    // 标记产品为已添加状态
    row.isAdded = true;

    //查询产品的bom需求
    request({
        url: "/bom/boms",
        method: "get",
        params: { materialId: row.productId }
    }).then(res => {
        bomList.value = res.data
        console.log(bomList.value);
    })

    products.value = row
    console.log(products.value);

    ElMessage.success('产品添加成功')
}

// 添加订单
const addOrder = () => {
    console.log(selectedOrder.value);
    if (selectedOrder.value) {
        formData.value.salesOrderId = selectedOrder.value.quotationId
    }
    orderDialogVisible.value = false
    ElMessage.success('已添加订单')
}

let options = ref([])
// 获取工艺路线
const getRouting = () => {
    request({
        url: '/process/index',
        method: 'get',
        params: {
            page: 1,
            size: 10000,
        }
    }).then(res => {
        console.log(res.data.records);
        options.value = res.data.records
    })
}
getRouting()



// 提交表单（改造后，实现前后端交互）
const submitForm = () => {
    let data = {
        productId: products.value.productId,
        routingId: products.value.routingId,
        planQuantity: products.value.quoteDetailsNumberOfSales,
    }
    console.log(data);

    formData.value.productionPlanDetails = data
    console.log(formData.value)
    request({
        url: '/production/plan/insert',
        method: 'post',
        data: formData.value
    }).then(res => {
        console.log(res);
        ElMessage.success('提交成功')
        emit('ref-table')
    })
}
// 取消表单
const cancelForm = () => {
    emit('ref-table')
}


const productDialogVisible = ref(false)
// 初始化表单数据
onMounted(() => { })

// 模拟产品数据
const productLists = ref([])

// 产品选择相关状态
const productSearch = ref('')
const productPage = ref(1)

// 过滤后的产品列表
const filteredProductList = ref([])

// 显示产品选择弹窗
const showProductDialog = () => {
    productDialogVisible.value = true
    productSearch.value = ''
    productPage.value = 1
    request({
        url: '/material/index',
        method: 'get',
        params: {
            page: 1,
            size: 10000,
        }
    }).then(res => {
        console.log(res.data.records);

        productLists.value = res.data.records
        filteredProductList.value = res.data.records
        console.log(filteredProductList.value);
    })
}

// 产品搜索
const handleProductSearch = () => {
    productPage.value = 1
}

// 清除搜索
const handleProductSearchClear = () => {
    productPage.value = 1
}

// 确认产品选择
const addProducts = (row) => {
    console.log(row);
    let p={ 
        productId: row.materialId,
        materialName: row.materialName,
        quoteDetailsUnit: row.unit,
        specificationsAndModels: row.specificationsAndModels,
        quoteDetailsNumberOfSales: row.planQuantity,
        isAdded: false // 初始化添加状态为false
    }
    row.isAdded = true;
    products.value = p
    console.log(products.value);
    ElMessage.success('产品添加成功')

}


// 确认产品选择
const confirmProductSelection = () => {
   
    productDialogVisible.value = false
    
}

</script>

<style scoped>
.el-table__row {
    cursor: pointer;
}

.el-table__row:hover {
    background-color: #f5f7fa;
}

.product-card {
    margin-top: 20px;
}
</style>